package com.sacc.controller;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.power.common.model.CommonResult;
import com.sacc.pojo.BaseUser;
import com.sacc.service.BaseUserService;
import com.sacc.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;


/**
 * @author 滚~韬
 * @date 2022/4/18 18:53
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private BaseUserService baseUserService;
    private final String APPID = "wxf3816c432e179088";
    private final String SECRET = "66bc191042f155e64f24317bd8691806";
    private final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    //用户登录请求
    @PostMapping("/login")
    public Object Login(@RequestParam String code){
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(URL)
                .queryParam("js_code",code)
                .queryParam("appid",APPID)
                .queryParam("secret",SECRET)
                .queryParam("grant_type","authorization_code");
        JSONObject jsonObject = JSONObject.parseObject(restTemplate.getForObject(builder.build().toString(), String.class));
        if(jsonObject.containsKey("openid")){
            //尝试添加用户进库
            baseUserService.Add(jsonObject.get("openid").toString());
            jsonObject.put("token",JwtUtil.generateToken((String) jsonObject.get("openid")));
            jsonObject.remove("session_key");
            return jsonObject;
        }else{
            return jsonObject;
        }
    }
    //添加或者更改手机号
    @PostMapping("/phone/add")
    private CommonResult AddPhone(@RequestParam(value = "code") String Code,@RequestParam String openId){
        Map<String,String> params=new HashMap<>();
        params.put("grant_type","client_credential");
        params.put("appid",APPID);
        params.put("secret",SECRET);
        ResponseEntity<String> responseEntity=restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type={grant_type}&appid={appid}&secret={secret}",String.class,params);
        Map map = JSONObject.parseObject(responseEntity.getBody(), Map.class);
        if(!StringUtils.isEmpty(map.get("errcode"))){
            return new CommonResult(false,"获取token参数有误");
        }
        if(!StringUtils.isEmpty(map.get("access_token"))){
            String accessToken=map.get("access_token").toString();
            String code=Code;
            Map<String,String> param = new HashMap<>();
            if(!StringUtils.isEmpty(code)){
                param.put("code",code);
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Accept", "application/json");
            HttpEntity<Map<String, String>> httpEntity = new HttpEntity< Map<String, String>>(param,headers);
            String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
            ResponseEntity<String> postResponseEntity=restTemplate.postForEntity(url,httpEntity,String.class);
            Map postMap=JSONObject.parseObject(postResponseEntity.getBody(),Map.class);
            if(!StringUtils.isEmpty(postMap.get("errcode"))){
                String errcode=postMap.get("errcode").toString();
                if(errcode.equals("-1")){
                    return new CommonResult(false,"系统繁忙，请稍后重试");
                }
                if(errcode.equals("40029")){
                    return new CommonResult(false,"code不存在或已过期，请重试");
                }
                if(errcode.equals("40013")){
                    return new CommonResult(false,"不合法AppId");
                }
                if(errcode.equals("0")){
                    JSONObject jsonObject = JSONObject.parseObject(postMap.get("phone_info").toString());
                    String phoneNumber = jsonObject.get("phoneNumber").toString();
                    baseUserService.AddPhoneNUmber(openId,phoneNumber);
                    return new CommonResult(true,"获取成功", phoneNumber);
                }
            }
        }
        return new CommonResult(false,"未获取手机号");
    }
    //得到手机号
    @GetMapping("/phone/get")
    private CommonResult GetPhone(@RequestParam String openId){
        return baseUserService.GetPhoneNUmber(openId);
    }
}